package com.leyou.common.advice;

import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.util.Arrays;

/**
 * @author 虎哥
 */
@Aspect
@Slf4j
public class CommonLogAdvice {

    @Around("within(@org.springframework.stereotype.Service *)")
    public Object handle(ProceedingJoinPoint jp){
        // 记录方法入参
        String methodName = jp.getSignature().getName();
        log.debug("方法{}正在被调用，入参：[{}]", methodName, Arrays.toString(jp.getArgs()));
        Object object = null;
        try {
            // 放行切点拦截到的service的方法
            object = jp.proceed();
            // 记录方法出参
            log.debug("方法{}调用完毕，结果：[{}]", methodName, JsonUtils.toJson(object));
            // 返回结果
            return object;
        } catch (Throwable throwable) {
            if(throwable instanceof LyException){
                log.debug("方法{}调用错误, 原因: {}", methodName, throwable.getMessage());
                throw (LyException) throwable;
            }
            log.error(throwable.getMessage(), throwable);
            throw new RuntimeException(throwable);
        }

    }
}
